package com.yl.zqy.controller.sys;

import com.yl.zqy.common.CustomException;
import com.yl.zqy.common.Result;
import com.yl.zqy.constant.ZQYConstant;
import com.yl.zqy.dto.SysRoleUserDTO;
import com.yl.zqy.entity.sys.SysRole;
import com.yl.zqy.enums.ResultCode;
import com.yl.zqy.service.sys.SysRoleService;
import com.yl.zqy.service.sys.SysRoleUserService;
import com.yl.zqy.vo.common.IPageVo;
import com.yl.zqy.vo.user.AuthMenusByRole;
import com.yl.zqy.vo.user.AuthUsersByRole;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

import static com.yl.zqy.constant.ZQYConstant.SUPER_ADMIN;

/**
 * <p>
 * 角色管理 前端控制器
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-28
 */
@RestController
@RequestMapping("/sysRole")
@Tag(name = "角色管理", description = "SysRoleController")
@RequiredArgsConstructor
public class SysRoleController {
    private final SysRoleService roleService;
    private final SysRoleUserService roleUserService;

    @PostMapping("/add")
    @Operation(summary = "新增角色", tags = "角色管理")
    public Result<Boolean> insertRole(@RequestBody SysRole role) {
        return roleService.insertRole(role);
    }

    @PutMapping("/update")
    @Operation(summary = "修改角色", tags = "角色管理")
    public Result<Boolean> updateRole(@RequestBody SysRole role) {
        Optional.ofNullable(role.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "ID不能为空！"));
        return roleService.updateRole(role);
    }

    @PutMapping("/update/status")
    @Operation(summary = "修改角色状态（启用or停用）", tags = "角色管理")
    public Result<Boolean> updateRoleStatus(@RequestBody SysRole role) {
        Optional.ofNullable(role.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "ID不能为空！"));
        Optional.ofNullable(role.getStatus()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "状态不能为空！"));
        return roleService.updateRoleStatus(role);
    }

    @DeleteMapping("/deleteById/{id}")
    @Operation(summary = "删除角色", tags = "角色管理")
    public Result<Boolean> deleteById(@Parameter(description = "id") @PathVariable(value = "id") String id) {
        Optional.ofNullable(id).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "ID不能为空！"));
        // 判断是否为 超级管理员角色  无法被删除
        if (SUPER_ADMIN.equals(id)) {
            throw new CustomException(ResultCode.SERVER_ERROR, "超级管理员角色无法被删除！");
        }
        // 判断角色下是否有授权的用户
        Long judgeRoleByUserCount = roleUserService.judgeRoleByUserCount(id);
        if (judgeRoleByUserCount > 0) {
            throw new CustomException(ResultCode.SERVER_ERROR, "当前角色下有授权的用户，不能删除！");
        }

        return Result.ok(roleService.removeById(id));
    }

    @GetMapping("/roleByPage")
    @Operation(summary = "获取角色分页数据", tags = "角色管理")
    public Result<IPageVo<SysRole>> roleByPage(
            @Parameter(description = "页号") @RequestParam(value = "current", defaultValue = ZQYConstant.CURRENT) int current,
            @Parameter(description = "页大小") @RequestParam(value = "size", defaultValue = ZQYConstant.SIZE) int size,
            @Parameter(description = "角色状态") @RequestParam(value = "status", required = false) String status,
            @Parameter(description = "条件查询（角色名称及编码）") @RequestParam(value = "query", required = false) String query) {

        return roleService.roleByPage(current, size, status, query);
    }

    @GetMapping("/getRoleNoAuthorizeUsers")
    @Operation(summary = "获取角色下待授权用户", tags = "角色管理")
    public Result<List<SysRoleUserDTO>> getRoleNoAuthorizeByUsers(
            @Parameter(description = "角色ID") @RequestParam(value = "roleId") String roleId,
            @Parameter(description = "条件查询（账号及姓名）") @RequestParam(value = "query", required = false) String query) {
        Optional.ofNullable(roleId).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "roleId不能为空！"));
        return roleService.getRoleNoAuthorizeByUsers(roleId, query);
    }

    @GetMapping("/getRoleAuthorize")
    @Operation(summary = "获取角色下已授权用户", tags = "角色管理")
    public Result<List<SysRoleUserDTO>> getRoleAuthorizeByUsers(
            @Parameter(description = "角色ID") @RequestParam(value = "roleId") String roleId,
            @Parameter(description = "条件查询（账号及姓名）") @RequestParam(value = "query", required = false) String query) {
        Optional.ofNullable(roleId).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "roleId不能为空！"));
        return roleService.getRoleAuthorizeByUsers(roleId, query);
    }

    @PostMapping("/roleAuthorizeUsers")
    @Operation(summary = "给角色授权用户", tags = "角色管理")
    public Result<Boolean> roleAuthorizeUsers(@RequestBody AuthUsersByRole auth) {
        Optional.ofNullable(auth.getRoleId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "roleId不能为空！"));
        return roleService.roleAuthorizeUsers(auth);
    }

    @GetMapping("/getRoleByMenus")
    @Operation(summary = "获取角色下已授权菜单", tags = "角色管理")
    public Result<List<String>> getRoleByMenus(
            @Parameter(description = "角色ID") @RequestParam(value = "roleId") String roleId) {
        Optional.ofNullable(roleId).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "roleId不能为空！"));
        return roleService.getRoleByMenus(roleId);
    }

    @PostMapping("/roleAuthorizeMenus")
    @Operation(summary = "给角色授权菜单", tags = "角色管理")
    public Result<Boolean> roleAuthorizeMenus(@RequestBody AuthMenusByRole auth) {
        Optional.ofNullable(auth.getRoleId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "roleId不能为空！"));
        return roleService.roleAuthorizeMenus(auth);
    }
}
